<?php
/**
 * Created by PhpStorm.
 * User: 郑好
 * Date: 2019/5/31
 * Time: 下午3:03
 */

namespace app\common;

use think\Exception;
use Log;

class BaiduTui
{
    use InstanceTrait;

    public function push($route)
    {
        if (config("app_env") != "prod") {
            return false;
        }

        $urls = [
            'https://343.cn',
            'https://m.343.cn',
        ];

        foreach ($urls as $k => $v) {
            $urls[$k] = $v . $route;
        }

        $api = 'http://data.zz.baidu.com/urls?site=343.cn&token=MKfnagNPkfRMzt02';

        try {
            $ch = curl_init();
            $options = array(
                CURLOPT_URL => $api,
                CURLOPT_POST => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POSTFIELDS => implode("\n", $urls),
                CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
            );

            curl_setopt_array($ch, $options);
            $result = curl_exec($ch);

            curl_close($ch);

            $result = json_decode($result, true);
            if (!isset($result["success"])) {
                \Log::error("" . $route . "百度链接推送失败：" . $result['message'], []);
                return false;
            }
            return true;
        } catch (Exception $e) {
            \Log::error("" . $route . "百度链接推送失败,发生错误：" . $e->getMessage(), []);
            return false;
        }
    }

    public function pushV2($route)
    {
        if (config("app_env") != "prod") {
            return false;
        }

        $urls = [
            'https://343.cn',
            'https://m.343.cn',
            'https://www.343.cn',
        ];

        try {
            foreach ($urls as $k => $v) {
                //                $urls[$k] = $v.$route;
                $api = 'http://data.zz.baidu.com/urls?site=' . $v . '&token=MKfnagNPkfRMzt02';
                $ch = curl_init();
                $options = array(
                    CURLOPT_URL => $api,
                    CURLOPT_POST => true,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_TIMEOUT => 5,
                    CURLOPT_POSTFIELDS => $v . $route,
                    CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
                );

                curl_setopt_array($ch, $options);
                $result = curl_exec($ch);

                curl_close($ch);

                $result = json_decode($result, true);
                if (!isset($result["success"])) {
                    \Log::error("" . $route . "百度链接推送失败：" . $result['message'], []);
                    return false;
                }
            }
            return true;
        } catch (Exception $e) {
            \Log::error("" . $route . "百度链接推送失败,发生错误：" . $e->getMessage(), []);
            return false;
        }
    }
}
